package com.spring.hotel.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.spring.hotel.common.JsonResponse;
import com.spring.hotel.common.utils.MD5Utils;
import com.spring.hotel.common.utils.SecurityUtils;
import com.spring.hotel.common.utils.SessionUtils;
import com.spring.hotel.entity.PageDTO;
import com.spring.hotel.entity.User;
import com.spring.hotel.entity.UserInfoDTO;
import com.spring.hotel.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/hotel/user")
public class UserController {
    @Autowired
    private UserService userService;

    //注册用户
    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public JsonResponse insert(@RequestBody User user) {
        user.setPassword(MD5Utils.md5(StringUtils.isNotBlank(user.getPassword()) ? user.getPassword() : "123456"));
        userService.save(user);
        return JsonResponse.success(null);
    }

    //登录
    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public JsonResponse login(User user) {
        System.out.println(user.getId()+user.getName()+user.getPassword());
        return userService.login(user);
    }

    //修改
    @RequestMapping(value = "/update",method = RequestMethod.PUT)
    public JsonResponse updateUser(@RequestBody User user) throws Exception {
        UserInfoDTO userInfo = SecurityUtils.getUserInfo();
        userService.updateById(user);
        if (user.getId().equals(userInfo.getId())) {
            SessionUtils.saveCurrentUserInfo(user);
        }
        return JsonResponse.success(null);
    }

    //删除
    @RequestMapping(value = "/delete/{id}",method = RequestMethod.DELETE)
    public JsonResponse delete(@PathVariable String id) {
        userService.removeById(id);
        return JsonResponse.success(null);
    }

    //分页查询
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public JsonResponse list(User user, PageDTO pageDTO) {
        return userService.pageList(user,pageDTO);
    }

}
